#include "VFileData.h"
#include "VParsing.h"
#include "VFunctions.h"
#include "VWords.h"

#include <QFileInfo>
#include <QDateTime>
#include <QDebug>

VFileData::VFileData(QString path, QString text)
{
	_path = path;
	_name = QFileInfo(path).fileName();
	_text = text;

    _word_data = new VWords(path, "", "", -1, VWords::KIND::FILE);
    VParsing parsing(text);
    parsing.parsing_words(_word_data);
    parsing.parsing_include(_include_list);
    _word_data->set_file((void*)this);
    _last_modify_time = QFileInfo(path).lastModified().toTime_t();
}

VFileData::~VFileData()
{
    delete _word_data;
}

VWords * VFileData::find_function(QString name)
{
    foreach (VWords* obj, _word_data->_list)
	{
        if ((obj->_kind == VWords::KIND::FUNCTION
             || obj->_kind == VWords::KIND::PROTOTYPE)
                && obj->_name == name)
		{
			return obj;
		}
	}
    return nullptr;
}

bool VFileData::has_main_function()
{
    auto ptr = _word_data->matching_child("main", VWords::KIND::FUNCTION, VWords::MATCH::NAME,
                               -1, VWords::MODE::ALL);

    if(ptr == nullptr)
    {
        ptr = _word_data->matching_child("主函数", VWords::KIND::FUNCTION, VWords::MATCH::NAME,
                                         -1, VWords::MODE::ALL);
    }

    if(ptr == nullptr)
    {
        return false;
    }
    else
    {
        return true;
    }
}

void VFileData::parsing_text(QString text)
{
	_text = text;
    VParsing parsing(text);
    parsing.parsing_words(_word_data);
    _word_data->set_file((void*)this);

    QList<VHeadFile> list;
    parsing.parsing_include(list);
    if(list_is_same(_include_list, list) == false)
    {
        _include_changed = true;
        _include_list = list;
    }
    _version ++;
}

VWords *VFileData::search_of_functon(int line)
{

    VWords* ptr = nullptr;
    int n = 999999;
    foreach (VWords* obj, _word_data->_list)
    {
        // 判断出所在的 function
        if(obj->_kind == VWords::KIND::FUNCTION
                && line > obj->_line)
        {
            int temp = line - obj->_line;
            if(temp < n)
            {
                n = temp;
                ptr = obj;
            }
        }
    }

    return ptr;
}

bool VFileData::list_is_same(QList<VHeadFile> &list1, QList<VHeadFile> &list2)
{
    if(list1.count() != list2.count())
    {
        return false;
    }

    for(int i=0; i<list1.count(); i++)
    {
        if(list1.at(i).name != list2.at(i).name ||
                list1.at(i).type != list2.at(i).type ||
                list1.at(i).path != list2.at(i).path)
        {
            return false;
        }
    }
    return true;
}
